package com.it.bannner;

public class SinglyLinkedList<T> {
    //头结点
      public   Node head = new Node(null);
    private Node tail = head;

    //添加
    public void addAll(T... datas) {
        //先判空
        if (null == datas) return;
        for (T data : datas) {
            if(tail.data== null){
                tail.data =  data;
            }
            else {
                //获取最后一个节点
                Node node = getLastNode();
                node.next = new Node(data);
            }
        }
        System.out.println(tail);
    }

    /**
     * 获取最后一个节点
     * @return
     */
    private Node getLastNode() {
        Node prv = null;
        Node next = tail;
        while (next != null) {
            prv = next;
            next = prv.next;
        }
        return prv;

    }

    //逆置
    public void reverse() {

        tail = head;
        Node newTail = tail.next;//这就是尾部
        if (null == tail || null == tail.next) return;
        Node cur = tail.next;
        Node temp;
        while (null != cur.next) {
            temp = cur.next;
            cur.next = tail;
            tail = cur;
            cur = temp;
        }
        cur.next = tail;

        tail = newTail;//给尾部设置null
        tail.next = null;

        head.next = cur;//新头部指向
    }

    //  @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        while (null != tail) {
            //   System.out.printf("tatil = "+list);
            builder.append(" ").append(tail.data);
            tail = tail.next;
        }

        return builder.toString();
    }

    //结点元素
    private class Node {
        @Override
        public String toString() {
            return "Node{" +
                    "next=" + next +
                    ", data=" + data +
                    '}';
        }

        Node next;
        T data;

        public Node(T data) {
            this.data = data;
        }
    }
}
